<?php
/**
 * Created by PhpStorm.
 * User: xkq
 * Date: 2018/4/9 0009
 * Time: 12:29
 */
set_include_path(dirname(dirname(__FILE__)));
include_once("inc/init.php");
if (!session_id()) session_start();
global $db;
    $upload_name = 'file';
    $targetDir   = $_SERVER['DOCUMENT_ROOT'] . '/upload/image/' . date('ym') . '/';
    $imgext = array('.jpg','.gif','.png','.jpeg');
    $fileext = array('.jpg','.gif','.png','.jpeg','.rar','.zip','.doc','.xls','.xlsx');

    $cleanupTargetDir = true; // Remove old files
    $maxFileAge = 5 * 3600; // Temp file age in seconds

    if (!file_exists($targetDir)) {
        mkdir($targetDir,0777,true);
    }
    if(!$_FILES[$upload_name]["name"]){
        exit('Failed to File null ');
    }
    $pos = strrpos($_FILES[$upload_name]["name"], '.');
    if ($pos !== false)
    {
        $file_type = substr($_FILES[$upload_name]["name"], $pos);
        if(!in_array($file_type,$fileext)) {
            exit('Failed to File type ');
        }
        //上传图片过大时对图片进行等比压缩
        if(in_array($file_type,$imgext)) {
            if($_FILES[$upload_name]['size']>(800*800)){
                compressed_image($_FILES[$upload_name]['tmp_name'],$_FILES[$upload_name]['tmp_name']);
            }
        }

    }

    $fileName = date('YmdHis') . rand(1000, 9999) . $file_type;
    $filePath = $targetDir . $fileName;

    // Chunking might be enabled
    $chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0;
    $chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0;

    // Remove old temp files
    if ($cleanupTargetDir) {
        if (!is_dir($targetDir) || !$dir = opendir($targetDir)) {
            exit('Failed to open temp directory.');
            //die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}');
        }

        while (($file = readdir($dir)) !== false) {
            $tmpfilePath = $targetDir . $file;

            // If temp file is current file proceed to the next
            if ($tmpfilePath == "{$filePath}.part") {
                continue;
            }

            // Remove temp file if it is older than the max age and is not the current file
            if (preg_match('/\.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) {
                @unlink($tmpfilePath);
            }
        }
        closedir($dir);
    }

    // Open temp file
    if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) {
        exit('Failed to open output stream');
        //die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}');
    }

    if (!empty($_FILES)) {
        if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES[$upload_name]["tmp_name"])) {
            exit('Failed to move uploaded file');
            //die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}');
        }

        // Read binary input stream and append it to temp file
        if (!$in = @fopen($_FILES[$upload_name]["tmp_name"], "rb")) {
            exit('Failed to open input stream');
            //die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
        }
    } else {
        if (!$in = @fopen("php://input", "rb")) {
            exit('Failed to open input stream');
            //die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
        }
    }

    while ($buff = fread($in, 4096)) {
        fwrite($out, $buff);
    }

    @fclose($out);
    @fclose($in);

    // Check if file has been uploaded
    if (!$chunks || $chunk == $chunks - 1) {
        // Strip the temp .part suffix off
        rename("{$filePath}.part", $filePath);
    }


    $file_path =  '/upload/image/' . date('ym') . '/'.$fileName;
echo json_encode(['file_path'=>$file_path]);
exit;

/**
 * 图片压缩
 * @param $imgsrc
 * @param $imgdst
 */
function compressed_image($imgsrc,$imgdst){
    list($width,$height,$type)=getimagesize($imgsrc);
    if($width*$height > 800*800){
        if($width > $height && $width >800){
            $new_width = 800;
            $new_height = round($height/(round($width/800)));
        }
        if($height > $width  && $height >800){
            $new_height = 800;
            $new_width = round($width/(round($height/800)));
        }
    }

    switch($type){
        case 1:
            break;
        case 2:
            $image_wp=imagecreatetruecolor($new_width, $new_height);
            $image = imagecreatefromjpeg($imgsrc);
            imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            //75代表的是质量、压缩图片容量大小
            imagejpeg($image_wp, $imgdst,75);
            imagedestroy($image_wp);
            imagedestroy($image);
            break;
        case 3:
            $image_wp=imagecreatetruecolor($new_width, $new_height);
            $image = imagecreatefrompng($imgsrc);
            imagecopyresampled($image_wp, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
            //75代表的是质量、压缩图片容量大小
            imagejpeg($image_wp, $imgdst,75);
            imagedestroy($image_wp);
            imagedestroy($image);
            break;
    }
}


